/**
 * 
 */
package com.oolong.account.web;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.oolong.account.exception.PasswordError;
import com.oolong.account.model.UserModel;
import com.oolong.account.service.ExtraService;
import com.oolong.account.util.ParamterCheck;

/**
 * @author beralee
 * 
 */
// 标记它是个SPRING的BEAN，是MVC里的C
@Controller
// 表示这个类就是login.do
@RequestMapping("/edituser.do")
public class EditUserController {
	Logger logger = Logger.getLogger(EditUserController.class);
	// 表示需要SPRING自动注入
	@Autowired
	private ExtraService extraService;
	String message = " ";

	// 表示这个方法是处理POST方法的
	@RequestMapping(method = RequestMethod.POST)
	// @RequestParam表示将页面上的元素赋给后面的变量，可直接在类里使用
	public String processSubmit(@RequestParam("user_id") Integer user_id,
			@RequestParam("oldpsw") String oldpsw,
			@RequestParam("newpsw") String newpsw,
			@RequestParam("email") String email, ModelMap model,
			HttpServletResponse response, HttpSession session) {
		message = " ";
		UserModel userModel = (UserModel) session.getAttribute("user");
		response.setContentType("text/html;charset=UTF-8");

		try {
			extraService.editUser(userModel.getId(), oldpsw, newpsw, email);
			// 校验密码
			if (!ParamterCheck.checkPassword(newpsw)) {
				message = "用户的密码只能为字母（大小写）或数字的组合，最大不得超过15位";
				model.addAttribute("message", message);
				return "deleteOutItem";
			}
			// 校验邮箱
			if (!ParamterCheck.checkMemo(email)) {
				message = "输入的所有邮箱总长度最大不得超过128位，请减少邮箱个数";
				model.addAttribute("message", message);
				return "deleteOutItem";
			}
			userModel.setEmail(email);
			userModel.setPassword(newpsw);
			message = "修改密码成功";
			session.setAttribute("user", userModel);
		} catch (PasswordError e) {
			message = "密码错误，不能修改";
		} catch (Exception e) {
			message = "修改信息异常，请联系管理员";
		}
		model.addAttribute("message", message);
		return "deleteOutItem";
	}

	@RequestMapping(method = RequestMethod.GET)
	// @RequestParam表示将页面上的元素赋给后面的变量，可直接在类里使用
	public String process(HttpServletResponse response, ModelMap model,
			HttpSession session) {
		message = " ";
		UserModel userModel = (UserModel) session.getAttribute("user");
		model.addAttribute("user", userModel);
		model.addAttribute("message", message);
		response.setContentType("text/html;charset=UTF-8");
		return "edituser";
	}
}
